import httpx
import logging
import json
from typing import Dict, Any, Optional
from datetime import datetime

logger = logging.getLogger(__name__)


class DingTalkNotifier:
    """钉钉机器人通知器"""
    
    def __init__(self, webhook_url: str):
        self.webhook_url = webhook_url
        self.timeout = 10.0
    
    async def send_text_message(self, content: str, at_mobiles: Optional[list] = None) -> bool:
        """发送文本消息"""
        payload = {
            "msgtype": "text",
            "text": {
                "content": content
            }
        }
        
        # 添加@功能
        if at_mobiles:
            payload["at"] = {
                "atMobiles": at_mobiles,
                "isAtAll": False
            }
        
        try:
            async with httpx.AsyncClient(timeout=self.timeout) as client:
                response = await client.post(
                    self.webhook_url,
                    json=payload,
                    headers={"Content-Type": "application/json"}
                )
                response.raise_for_status()
                
                result = response.json()
                if result.get("errcode") == 0:
                    logger.info(f"钉钉通知发送成功: {content[:50]}...")
                    return True
                else:
                    logger.error(f"钉钉通知发送失败: {result}")
                    return False
                    
        except Exception as e:
            logger.error(f"发送钉钉通知异常: {e}")
            return False
    
    async def send_rate_alert(
        self, 
        rule_id: str, 
        rule_description: str,
        jpy_cny_rate: float,
        jpy_usd_rate: float,
        change_pct: Optional[float] = None
    ) -> bool:
        """发送汇率告警"""
        # 计算1000日元折算
        cny_1000 = jpy_cny_rate * 1000
        usd_1000 = jpy_usd_rate * 1000
        
        # 构建消息内容
        content = f"🚨 [JPY汇率告警] {rule_description}\n"
        content += f"📊 当前汇率:\n"
        content += f"  JPY→CNY: {jpy_cny_rate:.6f} (1000JPY = {cny_1000:.2f}CNY)\n"
        content += f"  JPY→USD: {jpy_usd_rate:.6f} (1000JPY = {usd_1000:.2f}USD)\n"
        
        if change_pct is not None:
            change_emoji = "📈" if change_pct > 0 else "📉"
            content += f"{change_emoji} 日涨跌幅: {change_pct:+.2%}\n"
        
        content += f"⏰ 时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
        content += f"🔧 规则ID: {rule_id}"
        
        return await self.send_text_message(content)
